package cn.s1995.sloth.common.core.util;

import cn.s1995.sloth.common.core.constant.enums.hint.HintEnum;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * i18n 工具类
 *
 * @author sloth
 * @date 2022/3/30
 */
@UtilityClass
@Slf4j
public class MsgUtils {

    public static final String prefix = "biz.";

    /**
     * 通过code 和参数获取中文错误信息
     *
     * @param hint
     * @param objects
     * @return
     */
    public HintEnum getMessage(HintEnum hint, Object... objects) {
        MessageSource messageSource = getMessageSource();
        hint.setMsg(messageSource.getMessage(prefix + hint.getName(), objects, LocaleContextHolder.getLocale()));
        return hint;
    }

    /**
     * 通过code 获取中文错误信息
     *
     * @param code
     * @return
     */
    public String getMessage(String code) {
        MessageSource messageSource = getMessageSource();
        return messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
    }

    /**
     * 通过code 和参数获取中文错误信息
     *
     * @param code
     * @return
     */
    public String getMessage(String code, Object... objects) {
        MessageSource messageSource = getMessageSource();
        return messageSource.getMessage(code, objects, LocaleContextHolder.getLocale());
    }

    /**
     * security 通过code 和参数获取中文错误信息
     *
     * @param code
     * @return
     */
    public String getSecurityMessage(String code, Object... objects) {
        MessageSource messageSource = SpringContextHolder.getBean("securityMessageSource");
        return messageSource.getMessage(code, objects, LocaleContextHolder.getLocale());
    }

    /**
     * 获取MessageSource
     *
     * @return
     */
    private static MessageSource getMessageSource() {
        MessageSource messageSource = SpringContextHolder.getBean("slothMessageSource");
        return messageSource;
    }


}
